from apps.base.models import Role, Rights
from .forms import RoleAddForm, RoleEditForm
from service import res_json_data
from django.views.decorators.http import require_GET
from django.views.decorators.http import require_POST


# /api/v1/role/table/
@require_GET
def get_list_as_table(request):
    first_queryset = Role.objects.filter(is_deleted=False)
    res_data = []
    for item in first_queryset:
        item_data = item.json()
        res_data.append(item_data)

    return res_json_data.table_api(data=res_data)


# /api/v1/role/add/
@require_POST
def role_add(request):
    # print(request.POST)
    form = RoleAddForm(request.POST)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    name = form.cleaned_data.get('name')
    if Role.objects.filter(name=name, is_deleted=False).exists():
        msg = '该角色名称已存在,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)
    form.save()
    return res_json_data.success_api(msg='角色新增成功!')


# /api/v1/role/edit/
@require_POST
def role_edit(request):
    edit_id = request.POST.get('id')
    role_obj = Role.objects.filter(id=edit_id, is_deleted=False).first()
    if not role_obj:
        return res_json_data.not_found_api(msg="角色不存在或已删除!")

    form = RoleEditForm(request.POST, instance=role_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)

    name = form.cleaned_data.get('name')
    if Role.objects.exclude(id=edit_id).filter(name=name, is_deleted=False).exists():
        msg = '该角色名称已存在,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)

    form.save()
    return res_json_data.success_api(msg='角色修改成功!')


# /api/v1/role/del/
@require_POST
def role_del(request):
    del_id = request.POST.get('id')
    role_obj = Role.objects.filter(id=del_id, is_deleted=False).first()
    if not role_obj:
        return res_json_data.not_found_api(msg="角色不存在或已删除!")

    role_obj.is_deleted = True  # 标记为删除
    role_obj.save()
    return res_json_data.success_api(msg='角色删除成功!')


# /api/v1/role/is_enabled/
@require_POST
def role_is_enabled(request):
    enabled_id = request.POST.get('id')
    is_enabled = request.POST.get('is_enabled')
    role_obj = Role.objects.filter(id=enabled_id, is_deleted=False).first()
    current_role_name = str(role_obj.name)
    if not role_obj:
        return res_json_data.not_found_api(msg=f"{current_role_name}-该角色不存在或已删除!")

    # 禁用以及启用
    role_obj.is_enabled = is_enabled
    role_obj.save()
    msg = '角色启用成功!' if int(is_enabled) else '角色禁用成功!'
    return res_json_data.success_api(msg=msg)


# /api/v1/role/power_get/
@require_GET
def role_power_get(request):
    """获取角色的授权树 >> 跟权限表格树的逻辑是一样的!"""

    # - 1.树形结构展示所有的权限
    def get_children(item):
        children = []
        for child in item.rights_set.filter(is_deleted=False):
            child_data = child.json_power_tree()
            child_data['children'] = get_children(child)
            child_data["children"].sort(key=lambda x: x["sort"])
            children.append(child_data)
        return children

    first_queryset = Rights.objects.filter(pid__isnull=True, is_deleted=False)

    res_data = []
    for item in first_queryset:
        item_data = item.json_power_tree()
        item_data['children'] = get_children(item)
        item_data["children"].sort(key=lambda x: x["sort"])
        res_data.append(item_data)
    res_data.sort(key=lambda x: x["sort"])

    # 2. 获取当前角色所拥有的权限的id
    # (只要树中叶子节点的id,因为将其父节点的id一并传到前端的话,在树组件中选中父节点,子节点都会默认选中.> 但只传子节点的话,父节是会关联选中的)
    # > 体现在代码上,就只要没有pid指向该权限的那些权限的id,利用集合来实现!
    role_id = request.GET.get('id')
    role_obj = Role.objects.filter(id=role_id, is_deleted=False).first()
    right_select_queryset = role_obj.rights_list.filter(is_deleted=False)  # 正向查询
    r_ids = set()
    r_pids = set()
    for item in right_select_queryset:
        r_ids.add(item.id)
        r_pids.add(item.pid_id)
    select_list = list(r_ids - r_pids)  # 利用集合的相减得到叶子节点!!
    return res_json_data.tree_api(data=res_data, select=select_list)


# /api/v1/role/power_update/
@require_POST
def role_power_update(request):
    """给角色授权"""
    power_ids = request.POST.get("power_ids")
    role_id = request.POST.get("role_id")
    role_obj = Role.objects.filter(id=role_id, is_deleted=False).first()
    if not role_obj:
        return res_json_data.not_found_api(msg="授权的角色不存在或已删除!")
    if not power_ids:
        role_obj.rights_list.clear()
    else:
        # 先清空再重新添加
        power_list = power_ids.split(",")
        role_obj.rights_list.clear()
        role_obj.rights_list.add(*power_list)
    return res_json_data.success_api(msg="角色授权成功!")
